﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Top.Api.Stream.Connect;
using Top.Api.Stream.Message;
using System.Threading;
using Top.Api.Util;

namespace Top.Api.Stream
{
    public abstract class AbstractStreamImpl : IStreamImplementation
    {
        private ITopLogger log = new DefaultTopLogger();
        protected HttpResponse response;
        private StreamMsgConsumeFactory msgConsumeFactory;
        protected bool streamAlive = true;
        public AbstractStreamImpl(StreamMsgConsumeFactory msgConsumeFactory, HttpResponse response)
        {
            this.msgConsumeFactory = msgConsumeFactory;
            this.response = response;
        }

        public void nextMsg()
        {
            if (!streamAlive)
            {
                throw new Exception("Stream closed");
            }
            try{
                string line = response.getMsg() ;

                if (string.IsNullOrEmpty(line))
                {//正常读到流的末尾了。
                    streamAlive = false;
                    response.close();
                    return;
                }
                if (!string.IsNullOrEmpty(line))
                {
                    msgConsumeFactory.consume(delegate(object obj)
                        {
                            string parseString = parseLine(line);
                            if (!string.IsNullOrEmpty(parseString))
                            {
                                getMessageListener().onReceiveMsg(parseString);
                            }
                        });
                }

                //Thread msgParseThread = new Thread(delegate()
                //    {
                //        if (!string.IsNullOrEmpty(line))
                //        {
                //            string parseString = parseLine(line);
                //            if (!string.IsNullOrEmpty(parseString))
                //            {
                //                getMessageListener().onReceiveMsg(parseString);
                //            }
                //        }
                //    });
                //msgParseThread.Start();
               
            }
            catch (Exception e)
            {//这个时候抛出：SocketTimeoutException
                response.close();
                streamAlive = false;
                throw e;
            }
        }

        public bool isAlive()
        {
            return streamAlive;
        }

        public abstract ITopCometMessageListener getMessageListener();
        public abstract string parseLine(string msg);
        public abstract void onException(Exception ex);
        public abstract void close();

    }
}
